package com.yst.gateway.monitor.services.impl;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yst.gateway.monitor.common.utils.DateUtils;
import com.yst.gateway.monitor.common.utils.JsonUtils;
import com.yst.gateway.monitor.common.utils.LoginUserCache;
import com.yst.gateway.monitor.common.utils.UUIDGenerator;
import com.yst.gateway.monitor.dao.QzChannelInterfaceAddrMapper;
import com.yst.gateway.monitor.dao.QzChannelInterfaceAttachmentMapper;
import com.yst.gateway.monitor.dao.QzChannelInterfaceBcpMapper;
import com.yst.gateway.monitor.dao.QzChannelInterfaceMapper;
import com.yst.gateway.monitor.dao.QzChannelInterfaceSpbanksMapper;
import com.yst.gateway.monitor.dao.QzChannelInterfaceSpcardsMapper;
import com.yst.gateway.monitor.models.QzChannelInterface;
import com.yst.gateway.monitor.models.QzChannelInterfaceAddr;
import com.yst.gateway.monitor.models.QzChannelInterfaceAttachment;
import com.yst.gateway.monitor.models.QzChannelInterfaceBcp;
import com.yst.gateway.monitor.models.QzChannelInterfaceSpbanks;
import com.yst.gateway.monitor.models.QzChannelInterfaceSpcards;
import com.yst.gateway.monitor.services.QzInterfaceService;

/**
 * 前置系统接口管理业务实现类
 * @author sheungxin
 *
 */
@Service
@Scope("prototype")
public class QzInterfaceServiceImpl implements QzInterfaceService{
	
	@Autowired
	private QzChannelInterfaceMapper qzChannelInterfaceMapper;
	@Autowired
	private QzChannelInterfaceSpbanksMapper qzChannelInterfaceSpbanksMapper;
	@Autowired
	private QzChannelInterfaceSpcardsMapper qzChannelInterfaceSpcardsMapper;
	@Autowired
	private QzChannelInterfaceBcpMapper qzChannelInterfaceBcpMapper;
	@Autowired
	private QzChannelInterfaceAddrMapper qzChannelInterfaceAddrMapper;
	@Autowired
	private QzChannelInterfaceAttachmentMapper qzChannelInterfaceAttachmentMapper;
	
	@Override
	public PageInfo<QzChannelInterface> getByPage(int pageNum, int pageSize,
			Map<String, Object> paramMap) {
		PageHelper.startPage(pageNum, pageSize);
		return new PageInfo<QzChannelInterface>(qzChannelInterfaceMapper.selectAll(paramMap));
	}

	@Override
	public boolean add(QzChannelInterface t) {
		boolean flag=false;
		t.setIsNoDel(1);
		t.setCreator(LoginUserCache.getUserId());
		t.setCtime(DateUtils.getNowTime());
		if(qzChannelInterfaceMapper.insert(t)>0){
			flag=true;
		}
		return flag;
	}
	
	@Override
	public boolean update(QzChannelInterface t) {
		boolean flag=false;
		t.setModifier(LoginUserCache.getUserId());
		t.setUtime(DateUtils.getNowTime());
		t.setIsNoDel(null);
		if(qzChannelInterfaceMapper.updateByPrimaryKey(t)>0){
			flag=true;
		}
		return flag;
	}

	@Override
	public QzChannelInterface getById(String id) {
		return qzChannelInterfaceMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<QzChannelInterface> getByMap(Map<String, Object> paramMap) {
		return qzChannelInterfaceMapper.selectAll(paramMap);
	}

	@Override
	public boolean updateStatusById(String id) {
		boolean flag=false;
		QzChannelInterface t=getById(id);
		if(t!=null){
			QzChannelInterface upChannel=new QzChannelInterface();
			upChannel.setChannelInterId(id);
			upChannel.setEnableStatus(t.getEnableStatus()==1?2:1);
			upChannel.setModifier(LoginUserCache.getUserId());
			upChannel.setUtime(DateUtils.getNowTime());
			flag=qzChannelInterfaceMapper.updateByPrimaryKey(upChannel)>0?true:false;
		}
		return flag;
	}

	@Override
	public boolean delById(String id) {
		QzChannelInterface upChannel=new QzChannelInterface();
		upChannel.setChannelInterId(id);
		upChannel.setIsNoDel(0);
		upChannel.setModifier(LoginUserCache.getUserId());
		upChannel.setUtime(DateUtils.getNowTime());
		return qzChannelInterfaceMapper.updateByPrimaryKey(upChannel)>0?true:false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean addSpBank(Map<String, Object> paramMap) {
		boolean flag=true;
		if(paramMap!=null){
			try {
				String interId=(String) paramMap.get("interId");
				String channelId=(String) paramMap.get("channelId");
				//以本地字段中银行主键为key存储支持的银行信息
				Map<String, Object> spMap=JsonUtils.parse((String)paramMap.get("spJson"), HashMap.class);
				
				for(String key:spMap.keySet()){
					//支持的银行,code属性为渠道银行代码
					Map<String, Object> bkMap=(Map<String, Object>)spMap.get(key);
					
					//支持的银行
					QzChannelInterfaceSpbanks spbank=new QzChannelInterfaceSpbanks();
					spbank.setChaIntBankId(UUIDGenerator.getUUID());
					spbank.setInterfaceId(interId);//接口编号
					spbank.setChannelId(channelId);//渠道编号
					spbank.setLocalCode(key);//本地银行字典编号
					spbank.setChannelCode((String)bkMap.get("code"));//银行渠道代码
					//保存支持的银行信息
					qzChannelInterfaceSpbanksMapper.insert(spbank);
					
					for(String k:bkMap.keySet()){
						if(!k.equals("code")){
							//支持的卡类型信息
							Map<String, Object> klxMap=(Map<String, Object>)bkMap.get(k);
							QzChannelInterfaceSpcards spcard=new QzChannelInterfaceSpcards();
							spcard.setChaIntCardId(UUIDGenerator.getUUID());
							spcard.setSpbankId(spbank.getChaIntBankId());
							spcard.setLocalCode((String)klxMap.get("id"));
							spcard.setChannelCode((String)klxMap.get("code"));
							//保存支持的卡类型信息
							qzChannelInterfaceSpcardsMapper.insert(spcard);
							System.out.println();
							//获取支持卡类型的属性信息
							for(String k2:klxMap.keySet()){
								if(!k2.equals("id")&&!k2.equals("code")){
									QzChannelInterfaceBcp bcp=new QzChannelInterfaceBcp();
									bcp.setChaIntBcpId(UUIDGenerator.getUUID());
									bcp.setSpcardId(spcard.getChaIntCardId());
									bcp.setPropertyId(k2);
									//保存卡类型的属性信息
									qzChannelInterfaceBcpMapper.insert(bcp);
								}
							}
						}
					}
					
				}
			} catch (Exception e) {e.printStackTrace();
				flag=false;
			}
		}
		return flag;
	}

	@Override
	public boolean addDeploy(Map<String, Object> paramMap) {
		boolean flag=true;
		if(paramMap!=null){
			String interId=null;
			String deployInfo=null;
			if(paramMap.containsKey("interId")){
				interId=(String)paramMap.get("interId");
			}
			if(paramMap.containsKey("deployInfo")){
				deployInfo=(String)paramMap.get("deployInfo");
			}
			if(StringUtils.isNotBlank(interId)&&StringUtils.isNotBlank(deployInfo)){
				String[] deployArr=deployInfo.split("\n");
				for(String dy:deployArr){
					try{
						String[] array=dy.trim().split(",");
						QzChannelInterfaceAddr addr=new QzChannelInterfaceAddr();
						addr.setChanIntAddId(UUIDGenerator.getUUID());
						addr.setInterId(interId);
						addr.setIp(array[1]);
						addr.setPorts(Integer.parseInt(array[2]));
						addr.setUrl(array[3]);
						addr.setResponse(array[4]);
						addr.setDeploy(array[5]);
						addr.setType(Integer.parseInt(array[0]));
						qzChannelInterfaceAddrMapper.insert(addr);
					}catch (Exception e) {
						e.printStackTrace();
						flag=false;
						break;
					}
					
				}
			}
		}
		return flag;
	}

	@Override
	public List<QzChannelInterfaceSpbanks> getSpBankList(String interId) {
		return qzChannelInterfaceSpbanksMapper.selectSpBankList(interId);
	}

	@Override
	public List<QzChannelInterfaceSpcards> getSpCardList(String interId) {
		return qzChannelInterfaceSpcardsMapper.selectSpCardList(interId);
	}

	@Override
	public List<QzChannelInterfaceBcp> getBcpList(String interId) {
		return qzChannelInterfaceBcpMapper.selectBcpList(interId);
	}

	@Override
	public Map<String, Object> getSpMap(String interId) {
		Map<String, Object> spMap=new HashMap<String, Object>();
		spMap.put("spBankList", getSpBankList(interId));
		spMap.put("spCardList", getSpCardList(interId));
		spMap.put("bcpList", getBcpList(interId));
		spMap.put("deployList", getDeployInfo(interId));
		return spMap;
	}

	@Override
	public List<QzChannelInterfaceAddr> getDeployInfo(String interId) {
		Map<String, Object> paramMap=new HashMap<String, Object>();
		paramMap.put("interId", interId);
		return qzChannelInterfaceAddrMapper.selectAll(paramMap);
	}

	@Override
	public boolean modifySpBank(Map<String, Object> paramMap) {
		boolean flag=true;
		String interId=null;
		if(paramMap.containsKey("interId")){
			interId=(String)paramMap.get("interId");
			qzChannelInterfaceBcpMapper.deleteByInterId(interId);
			qzChannelInterfaceSpcardsMapper.deleteByInterId(interId);
			qzChannelInterfaceSpbanksMapper.deleteByInterId(interId);
			flag=addSpBank(paramMap);
		}else{
			flag=false;
		}
		return flag;
	}

	@Override
	public boolean modifyDeploy(Map<String, Object> paramMap) {
		boolean flag=true;
		String interId=null;
		if(paramMap.containsKey("interId")){
			interId=(String)paramMap.get("interId");
			qzChannelInterfaceAddrMapper.deleteByInterId(interId);
			flag=addDeploy(paramMap);
		}else{
			flag=false;
		}
		return flag;
	}

	@Override
	public void fileUpload(QzChannelInterfaceAttachment attachment, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			QzChannelInterfaceAttachment attach = new QzChannelInterfaceAttachment();
			response.setCharacterEncoding("UTF-8");
			FileItemFactory factory = new DiskFileItemFactory();			
			ServletFileUpload upload = new ServletFileUpload(factory);			
			List<FileItem> item = upload.parseRequest(request);		
			
			if(item.get(0).getName()!=null && !item.get(0).getName().isEmpty()){
				Iterator it = item.iterator();
				if(it!=null && it.hasNext()){
					String classPath = request.getSession().getServletContext().getRealPath("/");
								
					String filepath = classPath + "manage/upload/";
					File pfile = new File(filepath);
					if(!pfile.exists()){
						pfile.mkdirs();
					}
				
					File file = new File(classPath + "manage/upload/" + item.get(0).getName());
					
					while(it.hasNext()) {
						FileItem fi = (FileItem) it.next();	
						fi.write(file);					 					
					}
					
					attach.setChanIntAttId(UUIDGenerator.getUUID());
					attach.setChannelInterId(attachment.getChannelInterId());
					attach.setFileName(item.get(0).getName());
					attach.setFilePath(filepath);
					attach.setStatus(1);
					attach.setUploadPerson(LoginUserCache.getUserId());
					attach.setUploadTime(DateUtils.getNowTime());
					attach.setUtime(DateUtils.getNowTime());
					attach.setModifier(LoginUserCache.getUserId());
					qzChannelInterfaceAttachmentMapper.insert(attach);
				}	
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 
	@Override
	public boolean filedelById(String id) {
		QzChannelInterfaceAttachment attach = new QzChannelInterfaceAttachment();
		attach.setChanIntAttId(id);
		attach.setStatus(0);
		attach.setUtime(DateUtils.getNowTime());
		attach.setModifier(LoginUserCache.getUserId());
		int num = qzChannelInterfaceAttachmentMapper.updateByPrimaryKey(attach);
		if(num > 0) {
			return true;
		}else {
			return false;			
		}
	}

	@Override
	public List<QzChannelInterfaceAttachment> getAttchementList(String id) {
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("channelInterId", id);
		return qzChannelInterfaceAttachmentMapper.selectAll(id);
	}

	@Override
	public boolean checkInterName(String interName, String interId) {
		Map<String, Object> paramMap=new HashMap<String, Object>();
		paramMap.put("interName", interName);
		paramMap.put("interId", interId);
		return qzChannelInterfaceMapper.selectByInterName(paramMap).size()>0?true:false;
	}	
}
